package com.itheima.job;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Set;

public class MovementJob {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Scheduled(cron="0 30/* * * * ?")
    public void recommend() {
        System.out.println("开始动态推荐");
        Set<String> keys= stringRedisTemplate.keys("QUANZI_PUBLISH_RECOMMEND_*");
        if(CollectionUtil.isNotEmpty(keys)){
            for (String key : keys) {
                //获取推荐的用户id
                String userIdStr = key.replaceAll("QUANZI_PUBLISH_RECOMMEND_", "");//获取推荐用户id
                long userId = Long.parseLong(userIdStr);
                //清空原来推荐给此用户的数据
                Query query = new Query(Criteria.where("userId").is(userId));
                mongoTemplate.remove(query, RecommendMovement.class);
                //保存数据
                String pidArrStr = stringRedisTemplate.opsForValue().get(key);
                    String[] pidArr = pidArrStr.split(",");
                    for (String pidStr : pidArr) {
                        long pid = Long.parseLong(pidStr);
                        //通过mongo根据pid查询动态id
                        Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(pid)), Movement.class);

                        RecommendMovement recommendMovement = new RecommendMovement();
                        recommendMovement.setCreated(System.currentTimeMillis());
                        recommendMovement.setUserId(userId);//用户id
                        recommendMovement.setPid(pid);
                        recommendMovement.setPublishId(movement.getId());
                        recommendMovement.setScore(RandomUtil.randomDouble(70, 99));
                        mongoTemplate.save(recommendMovement);
                    }
            }
        }
        System.out.println("结束动态推荐");
    }
}
